package com.lanchetech.dao;

import com.lanchetech.entity.Sms;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Date;

@Mapper
public interface SmsMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Sms record);

    int insertSelective(Sms record);

    Sms selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Sms record);

    int updateByPrimaryKey(Sms record);

    /** 获取5分钟内的最新一条短信验证码
     * @param phone
     * @return
     */
    @Select("select * from sms " +
            "where phone = #{phone} " +
            "and created_at between #{startTime} and #{endTime} " +
            "order by created_at desc limit 1")
    Sms getLatestSmsInFiveMinutes(@Param("phone") String phone, @Param("startTime") Date startTime, @Param("endTime") Date endTime);

    /** 获取2分钟内的发送的短信数量
     * @param phone
     * @return
     */
    @Select("select 1 from sms " +
            "where phone = #{phone} " +
            "and created_at between date_add(now(), interval - 2 minute) and now() limit 1")
    Integer hasSmsInTwoMinutes(String phone);

    /** 获取该用户手机 24小时内发送了多少短信
     * @param phone
     * @return
     */
    @Select("select count(*) from sms " +
            "where phone = #{phone} " +
            "and to_days(created_at) = to_days(now())")
    Integer countTodaySms(String phone);

    /** 获取该用户ip 24小时内发送了多少短信
     * @param ip
     * @return
     */
    @Select("select count(*) from sms " +
            "where ip = #{ip} " +
            "and to_days(created_at) = to_days(now())")
    Integer countTodaySmsByIp(String ip);

    /** 获取30秒内的发送的短信数量
     * @param phone
     * @return
     */
    @Select("select 1 from sms " +
            "where phone = #{phone} " +
            "and created_at between #{startTime} and #{endTime} limit 1")
    Integer hasSmsInThirtySeconds(@Param("phone") String phone, @Param("startTime") Date startTime, @Param("endTime") Date endTime);
}